<template>
  <div
    class="my_button"
    :style="{ backgroundColor: buttonColor, width: buttonWidth }"
    @mouseenter="enterHandler"
    @mouseleave="leaveHandler"
    @click="changeColor"
  >
    {{ buttonText }}
    <!-- 自定义的提示框 -->
    <span class="tooltip" v-if="isHovered && showTips">这是提示框</span>
  </div>
</template>

<script setup>
// 定义传入的 props
const props = defineProps({
  buttonText: {
    type: String,
    required: true
  },
  buttonWidth: {
    type: String,
    default: '100px'
  },
  showTips: {
    type: Boolean,
    default: true
  },
  buttonInColor: {
    //控制鼠标点击以后颜色怎么改变，true是点击一次改变颜色，在点击又改变颜色，false是鼠标悬浮改变颜色，推出悬浮颜色回归
    type: Boolean,
    default: true
  }
})

import { ref } from 'vue'

const buttonColor = ref('rgb(54, 37, 37)') // 初始颜色
const isHovered = ref(false) // 控制鼠标悬浮状态

// 定义点击事件
const changeColor = () => {
  if (props.buttonInColor) {
    buttonColor.value =
      buttonColor.value === 'rgb(54, 37, 37)' ? 'rgb(100, 100, 100)' : 'rgb(54, 37, 37)'
  }
}

const enterHandler = () => {
  // 如果 showTips 为 true，才会显示提示框
  if (props.showTips) {
    isHovered.value = true
  }
  if (!props.buttonInColor) {
    buttonColor.value = 'rgb(252, 158, 73)'
  }
}

const leaveHandler = () => {
  // 如果 showTips 为 true，才会隐藏提示框
  if (props.showTips) {
    isHovered.value = false
  }
  if (!props.buttonInColor) {
    buttonColor.value = 'rgb(54, 37, 37)'
  }
}
</script>

<style>
.my_button {
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 5px;
  color: white;
  font-size: 12px;
  cursor: pointer;
  position: relative; /* 使tooltip相对于按钮定位 */
  transition: background-color 0.3s ease;
}

/* 提示框的样式 */
.tooltip {
  position: absolute;
  bottom: 100%; /* 提示框在按钮上方显示 */
  left: 50%;
  width: 100%;
  transform: translateX(-50%);
  padding: 5px;
  background-color: black;
  color: white;
  font-size: 10px;
  border-radius: 3px;
  opacity: 0.7;
  visibility: visible;
  z-index: 10;
}
</style>
